import React, { Component } from 'react';
import { connect } from 'dva';
import { Table, Icon, Spin, Button, Row, Input, Col, Form, Select, Checkbox } from 'antd';
import Editor from '@/utils/Editor';
import styles from './index.less';
const MyIcon = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1131883_m18hmgbwet.js', // 在 iconfont.cn 上生成
});
const formItemLayout = {
  labelCol: { span: 1 },
  wrapperCol: { span: 20 },
};
import { FormattedMessage } from 'umi-plugin-react/locale';
import { message } from 'antd/lib/index';
import UserSession from '@/UserSession';
import { knowledgeDialogSlots, knowledgeDialogNodeInfo } from '@/services/dialog';

@connect(({ SpecialCase, dialogCommon, loading }) => ({
  SpecialCase,
  dialogCommon,
  loading: loading.models.data,
}))
class SpecialCase extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dialogId: props.dialogId,
      nodeId: props.nodeId,
      stage: props.stage,
      stageId: '',
      specialCaseAdd: false,
      setting: [],
      currentSetting: {
        questions: [],
        // retryClearSlots: false,
        answer: '',
        clearSlots: [],
        id: '',
      },
      currentSettingIndex: -1,
      //specialAdd
      addValue: '',
      questions: [],
      slots: [],
      questionIndex: -1,
      content: '',
      robotId: '',
      settingId: '',
      currentPage: 1,
      pageSize: 10,
      editId: '',
      editIndex: 0,
    };
  }
  componentDidMount() {
    const { currentUser, dialogId, stage } = this.props;

    this.setState(
      {
        robotId: currentUser.robotId,
        dialogId: dialogId,
      },
      () => {
        switch (stage) {
          case undefined:
            this.getSetting();
            break;
          default:
            this.getInitByStage();
        }
        this.getDialogSlots();
      }
    );
  }

  getSetting = () => {
    const { robotId, dialogId } = this.state;

    const { dispatch } = this.props;
    dispatch({
      type: 'specialCase/getSetting',
      payload: {
        type: 'qa',
        robotId: robotId,
        dialogId: dialogId,
      },
      callback: res => {
        this.setState({
          settingId: res.settingId,
          setting: res.setting,
        });
      },
    });
  };

  getInitByStage = async () => {
    const { dialogId, nodeId, stage } = this.state;
    const { dispatch } = this.props;
    if (UserSession.isSystemKnowledge()) {
			let res = await knowledgeDialogNodeInfo({
        dialogId: dialogId,
        nodeId: nodeId,
        nodeType: stage,
        field: 'qa',
      });
      this.setState({
        setting: res.dialogStage.qa == null ? [] : res.dialogStage.qa,
        stageId: res.dialogStage.id,
      });
    } else {
      dispatch({
        type: 'dialogCommon/getStage',
        payload: {
          dialogId: dialogId,
          nodeId: nodeId,
          stage: stage,
          field: 'qa',
        },
        callback: res => {
          this.setState({
            setting: res.dialogStage.qa == null ? [] : res.dialogStage.qa,
            stageId: res.dialogStage.id,
          });
        },
      });
    }
  };

  getDialogSlots = async () => {
    const { dialogId } = this.state;
    const { dispatch } = this.props;
    if (UserSession.isSystemKnowledge()) {
      let res = await knowledgeDialogSlots({ dialogId })
      this.setState({
        slots: res==null?[]:res,
      })
    } else {
      dispatch({
        type: 'dialogCommon/getDialogSlots',
        payload: {
          dialogId: dialogId,
        },
        callback: res => {
          this.setState({
            slots: res,
          });
        },
      });
    }
  };

  addValue = () => {
    const { currentSetting, addValue } = this.state;
    switch (addValue.trim()) {
      case '':
        break;
      default:
        currentSetting.questions.push(addValue);
        this.setState({
          currentSetting: currentSetting,
          addValue: '',
        });
    }
  };

  addSlots = (name, index) => {
    const { addValue, questions, currentSetting } = this.state;
    if (index === -1) {
      const newValue = addValue + '<' + name + '>';
      this.setState({
        addValue: newValue,
      });
    } else {
      const newValue = currentSetting.questions[index] + '<' + name + '>';

      //questions[index] = newValue;
      currentSetting.questions[index] = newValue;
      this.setState({
        currentSetting: currentSetting,
      });
    }

    const resemblanceX = `resemblance${index}`;
    this.refs[resemblanceX].focus();
  };

  onChange = (e, type, index) => {
    switch (type) {
      case 'a':
        this.setState({
          addValue: e.target.value,
        });
        break;
      case 'b':
        const { currentSetting } = this.state;
        currentSetting.questions[index] = e.target.value;
        this.setState({
          currentSetting: currentSetting,
        });
        break;
    }
  };

  add = () => {
    this.setState({
      specialCaseAdd: true,
      currentSetting: {
        questions: [],
        // retryClearSlots: false,
        answer: '',
        clearSlots: [],
        // id: Date.parse(new Date()).toString(),
        id: '',
      },
    });
  };

  returnList = () => {
    this.setState({
      specialCaseAdd: false,
    });
  };

  changeQuestions = (q, i, type) => {
    const { currentSetting } = this.state;
    switch (type) {
      case 'del':
        currentSetting.questions.splice(i, 1);
        this.setState({
          currentSetting: currentSetting,
        });
        break;
      case 'up':
        currentSetting.questions.splice(i, 1);
        currentSetting.questions.unshift(q);
        this.setState({
          currentSetting: currentSetting,
        });
        break;
    }
  };

  changeQuestionsIndex = i => {
    this.setState({
      questionIndex: i,
    });
  };

  cleanSlot = event => {
    const { currentSetting } = this.state;
    currentSetting['retryClearSlots'] = !currentSetting['retryClearSlots'];
    this.setState({
      currentSetting: currentSetting,
    });
  };

  changeSlotValue = (val, index) => {
    const { currentSetting } = this.state;
    currentSetting.clearSlots[index] = val;
    this.setState({
      currentSetting: currentSetting,
    });
  };

  addClearSlots = () => {
    const { currentSetting } = this.state;
    currentSetting.clearSlots.push('');
    this.setState({
      currentSetting: currentSetting,
    });
  };

  closeSlot = index => {
    const { currentSetting } = this.state;
    currentSetting.clearSlots.splice(index, 1);
    this.setState({
      currentSetting: currentSetting,
    });
  };

  edit = (item, index) => {
    this.setState({
      currentSetting: item,
      specialCaseAdd: true,
      currentSettingIndex: index,
      editId: item.id,
      editIndex: index,
    });
  };

  save = () => {
    if (this.state.stage == undefined) {
      this.saveSetting();
    } else {
      this.saveStage();
    }
  };

  saveSetting = () => {
    const { currentSetting, settingId, dialogId } = this.state;
    const { dispatch } = this.props;
    const con = `editorRef`;
    if (currentSetting.questions.length <= 0) {
      message.info('请至少填写一条相似问');
      return;
    }
    if (this.refs[con].getUeditorContent().trim() == '') {
      message.info('问题回复不能为空');
      return;
    }

    currentSetting['answer'] = this.refs[con].getUeditorContent();

    this.setState({
      currentSetting: currentSetting,
    });
    dispatch({
      type: 'specialCase/doAdd',
      payload: {
        index: currentSetting.id,
        data: currentSetting,
        settingId: settingId,
        dialogId,
      },
      callback: res => {
        message.info(res.message);
        setTimeout(() => {
          this.setState(
            {
              specialCaseAdd: false,
            },
            () => {
              this.getSetting();
            }
          );
        }, 1500);
      },
    });
  };

  saveStage = () => {
    const { setting, stageId, currentSettingIndex, currentSetting, stage, editIndex } = this.state;
    const { dispatch } = this.props;
    const con = `editorRef`;
    if (currentSetting.questions.length <= 0) {
      message.info('请至少填写一条相似问');
      return;
    }
    if (this.refs[con].getUeditorContent().trim() === '') {
      message.info('问题回复不能为空');
      return;
    }
    currentSetting['answer'] = this.refs[con].getUeditorContent();
    this.setState({
      currentSetting: currentSetting,
    });

    if (currentSettingIndex < 0) {
      setting.unshift(currentSetting);
    } else {
      setting[currentSettingIndex] = currentSetting;
    }
    this.setState(
      {
        setting: setting,
      },
      () => {
        let settingSave = [];
        settingSave.push(setting[editIndex]);
        dispatch({
          type: 'dialogCommon/saveStage',
          payload: {
            id: stageId,
            field: 'qa',
            qa: settingSave,
            stage,
          },
          callback: res => {
            message.info(res.msg);
            setTimeout(() => {
              this.setState(
                {
                  specialCaseAdd: false,
                },
                () => {
                  this.getInitByStage();
                }
              );
            }, 1000);
          },
        });
      }
    );
  };

  deleteQa = (item, index) => {
    const { stage } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'specialCase/doDeleteQaList',
      payload: {
        specialId: item.id,
      },
      callback: res => {
        message.info(res.msg);
        if (stage) {
          this.getInitByStage();
        } else {
          this.getSetting();
        }
      },
    });
  };

  deleteQaFetch() {
    const { setting, robotId, dialogId, settingId, currentPage, pageSize } = this.state;
    const { dispatch } = this.props;
  }

  handleSubmitComment = val => {
    this.setState({
      currentPage: val,
    });
  };

  changePageSize = val => {
    this.setState({
      pageSize: val,
    });
  };

  specialList = type => {
    const { setting } = this.state;
    const columns = [
      {
        title: '用户问题',
        width: '60%',
        render: item => {
          return <div>{item.questions[0]}</div>;
        },
      },
      {
        title: '操作',
        width: '20%',
        render: (text, item, index) => {
          return (
            <div className={styles.pb}>
              <Button style={{marginRight:10}} onClick={() => this.edit(item, index)} type="primary" size='small' disabled={UserSession.whetherCanDelete()}>
                <MyIcon style={{ marginRight: 5 }} type="icon-bi" />
                <FormattedMessage id="app.dialog.question.edit" defaultMessage="Edit" />
              </Button>
              <Button
                size='small'
                type='danger'
                onClick={() => this.deleteQa(item, index)}
                disabled={UserSession.whetherCanDelete()}
              >
                <Icon size="small" type="delete" style={{ marginRight: 5 }} />
                <FormattedMessage id="app.dialog.question.delete" defaultMessage="out" />
              </Button>
            </div>
          );
        },
      },
    ];
    let loading = false;
    return (
      //主页
      <div>
        <div>
          <Button type="primary" style={{ marginBottom: '20px' }} onClick={this.add} disabled={UserSession.whetherCanDelete()}>
            添加
          </Button>
        </div>
        <Spin spinning={loading}>
          <Table
            columns={columns}
            dataSource={this.state.setting} //数据
            pagination={{
              // 分页
              size: 'small',
              total: setting.length,
              pageSize: 10, // 显示几条一页
              current: this.state.currentPage, // 当前页
              showSizeChanger: true, // 是否显示可以设置几条一页的选项
              showQuickJumper: true,
              onChange: this.handleSubmitComment,
              onShowSizeChange: this.changePageSize,
            }}
          />
        </Spin>
      </div>
    );
  };

  forMapSlotsOption = option => {
    return <Select.Option value={option.id}>{option.name}</Select.Option>;
  };

  /*currentSetting.clearSlots.map((itemId,index)=>(
    <Select value={itemId} style={{ width: '16%',marginRight:'10px' }} size="small" onChange={(value) => this.changeSlotValue(value,index)}>
    {
      this.state.slots.map((item)=>(
          <Select.Option value={item.id}>{item.name}</Select.Option>
        )
      )
    }
    </Select>
))*/
  forMap = (itemId, index) => {
    const { slots } = this.state;
    const OptionElem = slots.map(this.forMapSlotsOption);
    return (
      <span>
        <Select
          size="small"
          value={itemId}
          defaultValue="none"
          style={{ width: 120, marginLeft: 15 }}
          onChange={value => this.changeSlotValue(value, index)}
        >
          <Select.Option value="none">请选择词槽</Select.Option>
          {OptionElem}
        </Select>
        <Icon
          type="close-circle"
          onClick={() => this.closeSlot(index)}
          style={{ marginLeft: 5, cursor: 'pointer' }}
        />
      </span>
    );
  };

  specialAdd = () => {
    const { questions, slots, currentSetting } = this.state;
    const tagChild = currentSetting.clearSlots.map((itemId, index) => this.forMap(itemId, index));
    return (
      <div>
        <div>
          <div
            style={{ marginBottom: '20px', fontSize: '16px', width: '18%', cursor: 'pointer' }}
            onClick={this.returnList}
          >
            <Icon type="left" />
            &nbsp;&nbsp;<span>返回列表</span>
          </div>
          <Row>
            <Col xs={24}>
              <div className={styles.title}>
                <span>用户问题</span>
              </div>
            </Col>
          </Row>

          <div style={{ margin: '15px 0px 15px 10px', width: '100%' }}>
            <Input
              style={{ width: '85%' }}
              placeholder="请输入相似问题, 点击回车继续添加"
              className={styles.inputItem}
              value={this.state.addValue}
              maxLength={100}
              onChange={event => {
                this.onChange(event, 'a', -1);
              }}
              onPressEnter={this.addValue}
              onFocus={e => this.changeQuestionsIndex(-1)}
              ref={`resemblance-1`}
            />
            <span>
              <Icon
                type="plus-circle"
                style={{ fontSize: 20, marginLeft: 10, cursor: 'pointer', marginTop: 5 }}
                onClick={this.addValue}
              />
            </span>
            <div>
              {slots.map(slotItem => {
                return (
                  <Button
                    key={slotItem._id}
                    htmlType="button"
                    size="small"
                    style={{ marginRight: 10 }}
                    onClick={() => this.addSlots(slotItem.name, -1)}
                  >
                    &lt;{slotItem.name}&gt;
                  </Button>
                );
              })}
            </div>
          </div>

          {currentSetting.questions.map((q, i) => {
            return (
              <div style={{ width: '100%', margin: '15px 0px 15px 10px' }}>
                <div>
                  <Input
                    style={{ width: '85%' }}
                    className={styles.inputItem}
                    value={q}
                    onChange={event => {
                      this.onChange(event, 'b', i);
                    }}
                    maxLength={100}
                    onFocus={e => this.changeQuestionsIndex(i)}
                    ref={`resemblance${i}`}
                  />
                  <span>
                    <Icon
                      className="dynamic-delete-button"
                      type="close-circle"
                      style={{ fontSize: 20, marginLeft: 10, cursor: 'pointer', marginTop: 5 }}
                      onClick={() => this.changeQuestions(q, i, 'del')}
                    />
                    <Icon
                      type="arrow-up"
                      style={{ fontSize: 20, marginLeft: 10, cursor: 'pointer', marginTop: 5 }}
                      onClick={() => this.changeQuestions(q, i, 'up')}
                    />
                  </span>
                  <div>
                    {this.state.questionIndex === i
                      ? slots.map(slotItem => {
                          return (
                            <Button
                              key={slotItem._id}
                              htmlType="button"
                              size="small"
                              style={{ marginRight: 10 }}
                              onClick={() => this.addSlots(slotItem.name, i)}
                            >
                              &lt;{slotItem.name}&gt;
                            </Button>
                          );
                        })
                      : null}
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        <div style={{ margin: '20px 0px' }}>
          <Row>
            <Col xs={24}>
              <div className={styles.title}>
                <span>问题回复</span>
              </div>
            </Col>
          </Row>
          <div
            className="fuwenben"
            style={{ lineHeight: '20px', width: 500, zIndex: 1, margin: '15px 0px 15px 10px' }}
          >
            <Editor
              content={this.state.currentSetting.answer}
              name="content"
              id="content"
              height="300"
              width="400"
              ref="editorRef"
            />
          </div>
        </div>

        <div style={{ margin: '20px 0px' }}>
          <Row>
            <Col xs={24}>
              <div className={styles.title}>
                <span>词槽处理</span>
              </div>
            </Col>
          </Row>
          <Form.Item {...formItemLayout} label="">
            <div style={{ marginLeft: 10, display: 'inline-block', width: '100%' }}>
              {/*<Checkbox style={{width: 120,marginLeft: 15}} checked={currentSetting.retryClearSlots} onChange={() => this.cleanSlot()}>清空词槽</Checkbox>*/}
              <span style={{ marginLeft: 15 }}>清空词槽</span>
              {tagChild}
              <Button
                htmlType="button"
                type="primary"
                size="small"
                onClick={this.addClearSlots}
                style={{ marginLeft: 15 }}
                className={styles.addSlotBtn}
              >
                添加词槽
              </Button>
            </div>
          </Form.Item>

          <div style={{ margin: '15px 0px 15px 25px' }}>
            <Button type="primary" onClick={this.save}>
              保存
            </Button>
          </div>
        </div>
        {/*<div style={{margin:'20px 0px'}}>
          <Icon style={{transform: 'rotate(90deg)'}} type="minus"/>词槽处理
          <div style={{margin: '15px 0px 15px 10px'}}>
            <Checkbox style={{marginRight:'10px'}} checked={currentSetting.retryClearSlots} onChange={() => this.cleanSlot()}>清空词槽</Checkbox>
            {
              currentSetting.clearSlots.map((itemId,index)=>(
                <Select value={itemId} style={{ width: '16%',marginRight:'10px' }} size="small" onChange={(value) => this.changeSlotValue(value,index)}>
                  {
                    this.state.slots.map((item)=>(
                        <Select.Option value={item.id}>{item.name}</Select.Option>
                      )
                    )
                  }
                </Select>
              ))
            }
            <Button type="primary" size="small" onClick={this.addClearSlots}>添加</Button>
          </div>
          <div style={{margin: '15px 0px 15px 10px'}}>
            <Button type="primary">保存</Button>
          </div>
        </div>*/}
      </div>
    );
  };

  setSpecialVisible = () => {
    this.props.setSpecialVisible();
  };

  render() {
    const { type } = this.props;
    if (this.state.specialCaseAdd) {
      return <div>{this.specialAdd()}</div>;
    } else {
      return <div>{this.specialList(type)}</div>;
    }
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(SpecialCase);
